package cn.dgut.springboot.mini.transfer;

import cn.dgut.springboot.mini.dto.CustomerDTO;
import com.google.common.base.Strings;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 周智涛
 * @Description
 * @date 2019/12/12 20:21
 */
public class CustomerDtoTransfer {

    public static Specification getSpecification(CustomerDTO customerDTO){

        Specification specification=new Specification() {

            @Override
            public Predicate toPredicate(Root root,
                                         CriteriaQuery criteriaQuery,
                                         CriteriaBuilder cb) {

                List<Predicate> predicates=new ArrayList<Predicate>();

                if(!Strings.isNullOrEmpty(customerDTO.getName())){
                    predicates.add(cb.like(root.get("name"),"%"+customerDTO.getName()+"%"));
                }
                if(customerDTO.getBrith()!=null){
                    predicates.add(cb.like(root.get("birth"),"%"+customerDTO.getBrith()+"%"));
                }
                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };

        return specification;
    }


    public static PageRequest getPageRequest(CustomerDTO customerDTO){

        if(!Strings.isNullOrEmpty(customerDTO.getOrderBy())){
            Sort sort;
            if(customerDTO.getOrderDirection().toUpperCase().equals(Sort.Direction.DESC)){
                sort=Sort.by(Sort.Direction.DESC,customerDTO.getOrderBy());
            }else {
                sort=Sort.by(Sort.Direction.ASC,customerDTO.getOrderBy());
            }
            return PageRequest.of(customerDTO.getPage(),customerDTO.getPageSize(),sort);
        }else {
            return PageRequest.of(customerDTO.getPage(),customerDTO.getPageSize());
        }
    }
}
